﻿using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;

using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

using Authentication.User;
using Common;
namespace BuyRequest
{
    partial class SearchBuyRequest : PortalModuleBase, IActionable
    {
        #region Private Members
        BuyRequestLibs myBuyRequestLibs = new BuyRequestLibs(sysLibs.GetConnectionString);
        private readonly int maskLogoType = sysLibs.turnBitOn(0, consts.constIMGFileTypeBitPos) +
                                    sysLibs.turnBitOn(0, consts.constLOGOFileTypeBitPos);
        ArrayList productCatParams = new ArrayList();

        private string lastSQLCommand
        {
            get
            {
                if (Session["lastBuyRequestSQL"] == null) return "";
                return Session["lastBuyRequestSQL"].ToString();
            }
            set { Session["lastBuyRequestSQL"] = value; }
        }
        private int loginUserType
        {
            get
            {
                if (Session["loginUserType"] == null) return 0;
                return (int)Session["loginUserType"];
            }
        }
        private bool fAdminMode = false;  // Admin or owner login

        private bool SetBuyRequestStatus(GridView gvItem)
        {
            try
            {
                int requestId,userId;
                for (int i = 0; i < gvItem.Rows.Count; i++)
                {
                    if (!BuyRequestList.isRowChecked(i)) continue;
                    requestId = BuyRequestList.GetRequestId(i);
                    userId = BuyRequestList.GetBuyerId(i);
                    myBuyRequestLibs.UpdateBuyRequestStatus(requestId.ToString(),
                                                            BuyRequestList.SelectedStatusValue);
                    appLibs.MailChangeBuyRequestStatus(userId, BuyRequestList.GetRequestName(i), 
                                                       BuyRequestList.SelectedStatusText, "");

                }
                Common.sysLibs.ShowNotice(lblSearchMessage, "Đã thiết lập trạng thái theo yêu cầu", false);
            }
            catch (Exception exc)
            {
                Common.sysLibs.ShowNotice(lblSearchMessage, exc.ToString(), true);
                return false;
            }
            return true;
        }

        private bool ValidateData()
        {
            //Web-attack check
            if (!sysLibs.CheckStringSecurity(txtFrDate.Text.Trim()) ||
                !sysLibs.CheckStringSecurity(txtToDate.Text.Trim()) ||
                !sysLibs.CheckStringSecurity(txtUserAccount.Text.Trim()) ||
                !sysLibs.CheckStringSecurity(txtBuyRequetsName.Text.Trim()) ||
                !sysLibs.CheckStringSecurity(txtBuyRequestDesc.Text.Trim()))
            {
                sysLibs.ShowNotice(lblNotice, "Điều kiện tìm kiếm không hợp lệ.", true);
                return false;
            }
            return true;
        }

        private ArrayList getSelectedNodes(TreeView treeView)
        {
            ArrayList seletedNodes = new ArrayList();
            ArrayList arSyscodeId = new ArrayList();
            if (treeView.CheckedNodes.Count > 0)
            {
                foreach (TreeNode tn in treeView.CheckedNodes)
                {
                    seletedNodes.Add(tn.Value.Trim());
                }
            }
            return sysLibs.Translate(seletedNodes, "tm_productCat", "code", "syscodeId");
        }

        private string BuildQuerySQLCmd()
        {
            try
            {
                string SQLCmd1 = "SELECT DISTINCT a.requestId " +
                                " FROM tm_buy_request a INNER JOIN " +
                                " tm_users b ON a.RegisterBy = b.userId INNER JOIN " +
                                " tm_buyStatus c ON a.status = c.statusCode " +
                                " INNER JOIN tm_productType d ON a.productType = d.code";
                string SQLCmd2 = "SELECT a.requestId,a.Name1 AS name,a.description,a.processNotes," +
                                " a.RegisterDate,ISNULL(a.expireDate,'') AS expireDate,ISNULL(a.lastModifyDate,'') AS lastModifyDate,"+
                                "a.RegisterBy AS buyerId,"+ 
                                "CASE WHEN b.companyName1 IS NULL THEN b.fullName ELSE b.companyName1 END AS buyerName," +
                                "c.description1 AS status" +
                                //" ,ISNULL(a.clickCounter,0)AS clickCounter, ISNULL(b.clickCounter,0)AS clickCounterUser ," +
                                " FROM tm_buy_request a INNER JOIN " +
                                " tm_users b ON a.RegisterBy = b.userId INNER JOIN " +
                                " tm_buyStatus c ON a.status = c.statusCode ";
                string condStr = "", tmp;
                //Date range : 
                tmp = sysLibs.ConvertToSQLDateString(txtFrDate.Text.Trim());
                if (tmp.Trim() != "")
                    condStr += (condStr == "" ? "" : " AND ") + "(a.RegisterDate>='" + tmp.Trim() + "')";
                DateTime tmpDate = new DateTime();
                if (sysLibs.StringToDateTime(txtToDate.Text.Trim(), out tmpDate))
                {
                    //Date range : date have time so that we shoul move to the next day ???
                    tmp = sysLibs.ConvertToSQLDateString(tmpDate.AddDays(1));
                    if (tmp.Trim() != "")
                        condStr += (condStr == "" ? "" : " AND ") + "(a.RegisterDate<'" + tmp.Trim() + "')";
                }

                // Buy request name 
                if (txtBuyRequetsName.Text.Trim() != "")
                {
                    // If donot find the whole word:split the string into 
                    // several tokens combined by OR operator
                    if (chkFindEachWord.Checked)
                    {
                        string[] nameTokenSplit = txtBuyRequetsName.Text.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        ArrayList nameWordList = new ArrayList();
                        for (int idx = 0; idx < nameTokenSplit.Length; idx++)
                        {
                            nameWordList.Add(nameTokenSplit[idx].ToString());
                        }
                        tmp = "CONTAINS(a.name1,'" + sysLibs.MakeConditionStr(nameWordList, "\"", "\"", "OR") + "')";
                    }
                    else tmp = "CONTAINS(a.name1,'\"" + txtBuyRequetsName.Text.Trim() + "\"')";
                    condStr += (condStr == "" ? "" : " AND ") + "(" + tmp + ")";
                }

                // Request description 
                if (txtBuyRequestDesc.Text.Trim() != "")
                {
                    // If donot find the whole word:split the string into 
                    // several tokens combined by OR operator
                    if (chkFindEachWord.Checked)
                    {
                        string[] requestDescSplit = txtBuyRequestDesc.Text.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                        ArrayList requestWordList = new ArrayList();
                        for (int idx = 0; idx < requestDescSplit.Length; idx++)
                        {
                            requestWordList.Add(requestDescSplit[idx].ToString());
                        }
                        tmp = "CONTAINS(a.description,'" + sysLibs.MakeConditionStr(requestWordList, "\"", "\"", "OR") + "')";
                    }
                    else tmp = "CONTAINS(a.description,'\"" + txtBuyRequestDesc.Text.Trim() + "\"')";
                    condStr += (condStr == "" ? "" : " AND ") + "(" + tmp + ")";
                }

                if (txtUserAccount.Text.Trim() != "")
                {
                    condStr += (condStr == "" ? "" : " AND ") + "(account LIKE '" + consts.constSQLAllWildcard + txtUserAccount.Text.Trim() + consts.constSQLAllWildcard + "')";
                }

                //Product status
                if (cbStatus.Visible)
                {
                    if (cbStatus.SelectedValue.Trim() != Common.consts.constCbAllItemValue)
                        condStr += (condStr == "" ? "" : " AND ") + "(a.status='" + cbStatus.SelectedValue.Trim() + "')";
                }
                else // Only search Active product  
                    condStr += (condStr == "" ? "" : " AND ") + "(a.status='" + Common.consts.constStatusENABLE + "')";

                if (cbxExpire.Checked)
                    condStr += (condStr == "" ? "" : " AND ") + "(a.expireDate <='" + sysLibs.ConvertToSQLDateString(DateTime.Now.ToShortDateString()) + "')";

                //===================================
                //Product category from tree view
                //===================================
                ArrayList selectedNode = getSelectedNodes(tvProductCat.myTreeView);
                tmp = sysLibs.MakeConditionStr(selectedNode, "e.syscodeId=", "", "OR");
                if (tmp.Trim() != "")
                {
                    SQLCmd1 += " INNER JOIN tm_buy_request_syscodes e ON e.requestId = a.requestId";
                    condStr += (condStr == "" ? "" : " AND ") + "(" + tmp + ")";
                }

                //Combine all thing to an s SQL query
                SQLCmd1 += (condStr == "" ? "" : " WHERE " + condStr);
                SQLCmd2 += " WHERE a.requestId IN (" + SQLCmd1 + ")";
                return SQLCmd2;
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
            return "";
        }

        private void DoSearch(string SQLCmd)
        {
            try
            {
                if (SQLCmd.Trim() == "")
                {
                    sysLibs.ShowNotice(lblNotice, "Điều kiện tìm kiếm không hợp lệ.", true);
                    return;
                }
                sysLibs.ShowDebugMsg(lblDebugMessage, SQLCmd);
                pnlSearchResult.Visible = true;
                BuyRequestList.SQLCmd = SQLCmd;
                BuyRequestList.RequestData();

                //sysLibs.ShowNotice(lblNotice, SQLCmd, true);
                //return;

                //Only visible the SetStatus panel when 
                // - Admin mode
                // - There is some search result
                BuyRequestList.SetBottomPannelVisible(fAdminMode && BuyRequestList.SearchRecordCount > 0);
                lblSearchMessage.Visible = true;
                lblSearchMessage.Text = "Kết quả tìm :" + BuyRequestList.SearchRecordCount.ToString() + " yêu cầu tìm mua";
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        private void DoSearch()
        {
            lastSQLCommand = BuildQuerySQLCmd();
            DoSearch(lastSQLCommand);
        }

        private void LoadStatusList()
        {
            try
            {
                DataTable dt = myBuyRequestLibs.GetBuyRequestStatus();
                cbStatus.Items.Clear();
                if (dt != null && dt.Rows.Count > 0)
                {

                    ListItem item = new ListItem();

                    //them "Tat ca"
                    item = new ListItem();
                    item.Value = Common.consts.constCbAllItemValue;
                    item.Text = Common.consts.constCbAllItemText;
                    cbStatus.Items.Add(item);

                    foreach (DataRow dr in dt.Rows)
                    {
                        item = new ListItem();
                        item.Value = dr["statusCode"].ToString();
                        item.Text = dr["description1"].ToString();

                        cbStatus.Items.Add(item);
                    }
                }
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        private int GetExpireBuyRequeset()
        {
            string SQLCmd = "SELECT count(requestId) FROM tm_buy_request WHERE expireDate <= '" + sysLibs.ConvertToSQLDateString(DateTime.Now) + "'";
            return sysLibs.ExecuteScalar(SQLCmd, sysLibs.GetConnectionString);
        }

        private int GetNewBuyRequeset(string status)
        {
            string SQLCmd = "SELECT count(requestId) FROM tm_buy_request a INNER JOIN  tm_users b ON a.RegisterBy = b.userId INNER JOIN  tm_buyStatus c ON a.status = c.statusCode  INNER JOIN tm_productType d ON a.productType = d.code  WHERE status = '" + status + "'";
            return sysLibs.ExecuteScalar(SQLCmd, sysLibs.GetConnectionString);
        }
        private void ShowSatisticsInfo()
        {
            int j = GetExpireBuyRequeset();
            btntimMuaHetHan.Text = j + " hết hạn: ";

            int k = GetNewBuyRequeset(consts.constStatusNEW);
            btnTimMuaMoiDang.Text = k + " mới đăng.";
        }
        #endregion

        #region Public Methods
     
        #endregion

        #region Optional Interfaces

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Registers the module actions required for interfacing with the portal framework
        /// </summary>
        /// <value></value>
        /// <returns></returns>
        /// <remarks></remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        public ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection Actions = new ModuleActionCollection();
                Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
                return Actions;
            }
        }

        #endregion
        #region Event Handlers
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
                fAdminMode = false;
                if (UserId > 0)
                {
                    lblNotice.Visible = lblNotice.Text != "";
                    fAdminMode = userRoles.IsBuyRequestManager(loginUserType);
                }
                lblNotice.Visible = false;
                BuyRequestList.btnProcessText = "Đồng ý";
                BuyRequestList.curPortalId = PortalId;
                BuyRequestList.PageSize = Common.systemSettings.sysNoOfSearchResultPerPage;

                //Set implemented function to process Status button click
                BuyRequestList.ProcessSelectedFunc = SetBuyRequestStatus;
                BuyRequestList.SetBottomPannelVisible(fAdminMode);

                // If login user does not have admin permission ,
                // hide select checkbox, status 
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName._check, fAdminMode);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName.status, fAdminMode);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName._contact, true);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName.name, true);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName.registerDate, fAdminMode);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName.lastModifyDate, fAdminMode);
                BuyRequestList.SetColumnVisible(controls_buyRequestList.columnName.expireDate, fAdminMode);
                BuyRequestList.SetDeleteButtonVisible = fAdminMode;

                if (!Page.IsPostBack)
                {
                    ShowSatisticsInfo();
                    lblSearchMessage.Visible = false;
                    pnlSearchResult.Visible = false;

                    tvProductCat.parentFldName = "parentCode";
                    tvProductCat.textFldName = "description1";
                    tvProductCat.valueFldName = "code";
                    tvProductCat.dataTableName = "tm_productCat";

                    lblUserAccount.Visible = fAdminMode;
                    txtUserAccount.Visible = fAdminMode;
                    lblStatus.Visible = fAdminMode;
                    cbStatus.Visible = fAdminMode;
                    cbxExpire.Visible = fAdminMode;
                    //gan du lieu cho combo box
                    LoadStatusList();

                    //Display last querry list
                    if (Request["goLastList"] != null)
                    {
                        if (lastSQLCommand != "") DoSearch(lastSQLCommand);
                    }
                }
                hplTuNgay.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtFrDate);
                hplDenNgay.NavigateUrl = DotNetNuke.Common.Utilities.Calendar.InvokePopupCal(txtToDate);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (!ValidateData()) return;
            DoSearch();
        }
        protected void btnReset_Click(object sender, EventArgs e)
        {
            pnlSearchResult.Visible = false;
            txtFrDate.Text = "";
            txtToDate.Text = "";
            txtBuyRequestDesc.Text = "";
            txtBuyRequetsName.Text = "";
            txtUserAccount.Text = "";
            chkFindEachWord.Checked = false;
            cbStatus.SelectedIndex = 0;
            lblSearchMessage.Visible = false;
            cbxExpire.Checked = false;
        }
        protected void btntimMuaHetHan_Click(object sender, EventArgs e)
        {
            btnReset_Click(null, null);
            cbxExpire.Checked = true;
            DoSearch();
        }
        protected void btnTimMuaMoiDang_Click(object sender, EventArgs e)
        {
            btnReset_Click(null, null);
            cbStatus.SelectedValue = Common.consts.constStatusNEW;
            DoSearch();
        }
        #endregion
    }
}

